package com.k8sops.backend.config;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.FileReader;
import java.io.IOException;

@Configuration
public class K3sAuthenticationConfig {

    @Value("${kubernetes.api.server:https://101.42.243.192:6443}")
    private String apiServer;

    @Value("${kubernetes.api.token:K107b19bc33fb86484aef7d0ffd68c197eae18e980f5ad40695f64059d72473f210::server:bb5c10c97a982f5e4ea2dc308dab0a81}")
    private String apiToken;

    @Value("${kubernetes.config.path:/Users/anpy/personal/develop/AI/devops/k8s-ops-backend/src/main/resources/k3s-remote.yaml}")
    private String kubeConfigPath;
    
    @Bean
    @Primary
    public ApiClient k3sApiClient() throws IOException {
        System.out.println("正在加载K3s配置文件: " + kubeConfigPath);
        
        try {
            // 尝试使用kubeconfig文件进行认证
            io.kubernetes.client.util.KubeConfig kubeConfig = io.kubernetes.client.util.KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath));
            System.out.println("成功加载kubeconfig文件");
            System.out.println("当前上下文: " + kubeConfig.getCurrentContext());
            System.out.println("集群服务器: " + kubeConfig.getServer());
            
            ApiClient client = io.kubernetes.client.util.ClientBuilder.kubeconfig(kubeConfig).build();
            
            // 禁用SSL验证（在生产环境中应该启用）
            client.setVerifyingSsl(false);
            
            System.out.println("成功创建K3s API客户端");
            return client;
        } catch (Exception e) {
            System.err.println("加载kubeconfig文件失败: " + e.getMessage());
            e.printStackTrace();
            
            // 如果kubeconfig文件加载失败，尝试使用API令牌认证
            System.out.println("尝试使用API令牌认证...");
            ApiClient client = ClientBuilder.standard().build();
            client.setBasePath(apiServer);
            client.setVerifyingSsl(false);
            
            // 处理K3s特殊的令牌格式
            String token = apiToken;
            if (token.contains("::server:")) {
                token = token.split("::server:")[0];
            }
            
            // 设置认证头
            client.addDefaultHeader("Authorization", "Bearer " + token);
            
            System.out.println("成功创建K3s API客户端（使用令牌认证）");
            return client;
        }
    }
}
